package com.gxa.pingan.controller;

import com.gxa.pingan.common.ExceptionCode;
import com.gxa.pingan.common.JsonResult;
import com.gxa.pingan.exception.BusinessException;
import com.gxa.pingan.pojo.Manager;
import com.gxa.pingan.service.ManagerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @version fi
 * @Author lonny
 * @Date 2021/10/25 16:50
 */

@CrossOrigin
@RestController
@Transactional(rollbackFor = Throwable.class)
@RequestMapping(value = "/mng")
@Api(value = "执行系统管理员操作的控制器", tags = "系统用户接口的api")
public class ManagerController {


    private final ManagerService managerService;


    public ManagerController(ManagerService managerService) {
        this.managerService = managerService;
    }

    /**
     * 默认每页10行数据
     */
    private static final Integer SIZE = 10;

    @PostMapping("/inset")
    @ApiOperation("添加管理员,id自动注入,不需要传参")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "manager", name = "manager", paramType = "body", required = true),
            @ApiImplicitParam(value = "姓名", name = "name", required = true),
            @ApiImplicitParam(value = "电话", name = "phone", required = true),
            @ApiImplicitParam(value = "邮箱", name = "email", required = true),
            @ApiImplicitParam(value = "密码", name = "password", required = true),
            @ApiImplicitParam(value = "是否可用", name = "inUsed", required = true),
            @ApiImplicitParam(value = "权限组", name = "role", required = true)
    })
    public Map<String, Object> add(@RequestBody Manager manager) throws Exception {
        int i = managerService.addManager(manager);
        JsonResult jsonResult = new JsonResult();
        int size = managerService.size();
        jsonResult.setCode(String.valueOf(i));
        jsonResult.put("total", size);
        return jsonResult.getDataMap();
    }

    @PostMapping(value = "/update")
    @ApiOperation("修改管理员 手机号 密码,邮箱,权限(不包含是否可用)，更改的手机号和邮箱一致，会提示已存在")
    @ApiImplicitParam(value = "manager", name = "manager", paramType = "body", required = true)
    public Map<String, Object> update(@RequestBody Manager manager) throws Exception {
        int i = managerService.updateManager(manager);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(String.valueOf(i));
        jsonResult.setData(manager);
        return jsonResult.getDataMap();
    }

    @PostMapping(value = "/updateIn")
    @ApiOperation("修改管理员是否可用,无需查询是否存在,点击之后直接更改状态")
    @ApiImplicitParam(value = "id", name = "id", paramType = "query", required = true)
    public Map<String, Object> updateIn(Long id) throws Exception {
        managerService.updateInUsed(id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        return jsonResult.getDataMap();
    }

    @ApiOperation("删除管理员,id为被删除管理员的集合,可以多个 :例如1,2 ,则删除id为1，2的管理员")
    @PostMapping("/delete")
    @ApiImplicitParam(name = "ids", value = "ids", paramType = "query", required = true)
    public Map<String, Object> delete(String ids) throws Exception {
        int i = managerService.deleteManager(ids);
        JsonResult jsonResult = new JsonResult();
        int size = managerService.size();
        jsonResult.setCode("1");
        jsonResult.put("删除条数", i);
        jsonResult.put("total", size);
        System.out.println(size);
        return jsonResult.getDataMap();
    }

    @ApiOperation("管理员登录")
    @PostMapping("/login")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "phone", name = "phone", paramType = "query", required = true),
            @ApiImplicitParam(value = "password", name = "password", paramType = "query", required = true)
    })
    public Map<String, Object> login(String phone, String password, HttpServletRequest request) throws Exception {
        Manager manager = managerService.login(phone, password);
        String role = manager.getRole();
        String[] split = role.split(",");
        HttpSession session = request.getSession();
        UUID uuid = UUID.randomUUID();
        String replace = uuid.toString().replace("-", "");
        System.out.println(replace);
        session.setAttribute("token", replace);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(manager);
        jsonResult.put("role", split);
        jsonResult.put("token", replace);
        return jsonResult.getDataMap();
    }

    @ApiOperation("全查询,页码需要大于0")
    @PostMapping("/all")
    @ApiImplicitParam(value = "page", name = "page", paramType = "query", required = true, dataType = "manager")
    public Map<String, Object> all(Integer page) throws Exception {

        List<Manager> all = managerService.findAll(page, SIZE);
        System.out.println(all);
        int size = managerService.size();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(all);
        jsonResult.put("total", size);
        return jsonResult.getDataMap();
    }

    @ApiOperation("找回密码")
    @PostMapping("/retrieve")
    public Map<String, Object> retrieve(String code, String phone, String email, String newPwd, HttpServletRequest req) throws Exception {
        HttpSession session = req.getSession();
        Object phoneOrEmail = session.getAttribute("phoneOrEmail");
        Object captcha = session.getAttribute("captcha");
        JsonResult jsonResult = new JsonResult();
        if ((phoneOrEmail.equals(phone) || phoneOrEmail.equals(email))) {
            if (captcha.equals(code)) {
                System.out.println("phoneOrEmail:" + phoneOrEmail);
                System.out.println("captcha:" + captcha);
                Manager retrieve = managerService.Retrieve(phone, email, newPwd);
                jsonResult.setCode("1");
                jsonResult.setData(retrieve);
                return jsonResult.getDataMap();
            } else {
                throw new BusinessException(ExceptionCode.PIN_ERROR);
            }
        } else {
            throw new BusinessException(ExceptionCode.retrieve_FALSE);
        }
    }

    @ApiOperation("登出")
    @PostMapping("/logout")
    public void logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("token");
    }
}



